/**
 * @author zhouwr
 * @date 2020-11-04 22:25
 * @description 网络异步请求
 */
const Request = function (baseUrl, token) {
  // 全局配置axios
  axios.defaults.baseURL = baseUrl
  axios.defaults.timeout = 20000
  axios.defaults.crossDomain = true
  axios.defaults.withCredentials = true

  const err = (error) => {
    if (error.response) {
      let that = this
      let data = error.response.data
      console.log(error)
      console.log(data)
      console.log('------异常响应------', token)
      console.log('------异常响应------', error.response.status)
      switch (error.response.status) {
        case 403:
          alert('拒绝访问')
          break
        case 500:
          if (token) {
            /* 正式环境需要修改地址和端口号 */
            window.location.replace("http://127.0.0.1:3000")  // 跳转后没有后退功能
            alert('登录已过期，请重新登录')
          }
          break
        case 404:
          alert('很抱歉，资源未找到!')
          break
        case 504:
          alert('网络超时')
          break
        case 401:
          alert('未授权，请重新登录')
          if (token) {
            store.dispatch('Logout').then(() => {
              setTimeout(() => {
                window.location.reload()
              }, 1500)
            })
          }
          break
        default:
          alert(`请重新登录`)
          break
      }
    }
    return Promise.reject(error)
  }

  axios.interceptors.request.use(
    (config) => {
      const token = editor.TOKEN
      if (token) {
        config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
      }
      if (config.method === 'get') {
        if (config.url.indexOf('sys/dict/getDictItems') < 0) {
          config.params = {
            _t: Date.parse(new Date()) / 1000,
            ...config.params,
          }
        }
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  axios.interceptors.response.use((response) => {
    return response.data
  }, err)
}

Request.prototype = {
  //post
  postAction: function (url, parameter) {
    return axios({
      url: url,
      method: 'post',
      data: parameter,
    })
  },

  //post method= {post | put}
  httpAction: function (url, parameter, method) {
    return axios({
      url: url,
      method: method,
      data: parameter,
    })
  },

  //put
  putAction: function (url, parameter) {
    return axios({
      url: url,
      method: 'put',
      data: parameter,
    })
  },

  //get
  getAction: function (url, parameter) {
    return axios({
      url: url,
      method: 'get',
      params: parameter,
    })
  },

  //deleteAction
  deleteAction: function (url, parameter) {
    return axios({
      url: url,
      method: 'delete',
      params: parameter,
    })
  },
}

export {Request}
